﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Swift;
using SCM;
using MJ;

public class LoginUI : UIBase
{
    public InputField SrvAddr;
    public InputField Acc;
    public InputField Pwd;
    public Text Tips;

    protected override void Starting()
    {
        var srvAddr = PlayerPrefs.GetString("ServerAddress", "119.23.110.78");
        var acc = PlayerPrefs.GetString("Account", "");
        var pwd = PlayerPrefs.GetString("Password", "");
        SrvAddr.text = srvAddr;
        Acc.text = acc;
        Pwd.text = pwd;
    }

    public override void Show()
    {
        base.Show();
        SetTips("");
    }

    // 执行登录操作
    public void OnLogin()
    {
        var srvAddr = SrvAddr.text;
        var acc = Acc.text;
        var pwd = Pwd.text;

        if (acc == null || acc.Trim().Length == 0)
        {
            SetTips("用户名不能为空");
            return;
        }

        // 连接服务器
        var gc = GameCore.Instance;
        var nc = gc.Get<NetCore>();
        SetTips("连接服务器 ...");
        nc.Connect2Peer(srvAddr, 9001, (conn, reason) =>
        {
            if (conn == null)
                SetTips(reason);
            else
            {
                gc.ServerConnection = conn;

                // 登录
                SetTips("请求登录 ...");
                var buff = conn.Request2Srv("Login", (data) =>
                {
                    var ok = data.ReadBool();
                    if (ok)
                    {
                        PlayerPrefs.SetString("ServerAddress", srvAddr);
                        PlayerPrefs.SetString("Account", acc);
                        PlayerPrefs.SetString("Password", pwd);

                        SetTips("登录成功");
                        GameCore.Instance.MeID = acc;
                        GameCore.Instance.MeInfo = data.Read<UserInfo>();
                        Hide();
                    }
                    else
                    {
                        SetTips("登录失败");
                        conn.Close();
                    }
                    
                }, (conntected) =>
                {
                    SetTips("登录超时");
                    if (conntected)
                        conn.Close();
                });

                buff.Write(acc);
                buff.Write(pwd);
                conn.End(buff);
            }
        });
    }

    void SetTips(string tips)
    {
        Tips.text = tips;
    }
}
